<template>
  <div>
    <el-button class="el-icon-s-home" @click="openDialog1">添加地址</el-button>
    <el-table :data="address" style="width: 100%">
      <el-table-column prop="name" label="姓名" width="180"> </el-table-column>
      <el-table-column prop="phone" label="电话" width="180"> </el-table-column>
      <el-table-column prop="detailedAddress" label="地址" width="500">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="openDialog2(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加地址开始 -->
    <el-dialog
      title="添加地址"
      :visible.sync="dialogVisible1"
      width="30%"
      :before-close="handleClose1"
    >
      <!-- 添加地址表单开始 -->
      <el-form label-position="right" label-width="80px" :model="addAddress">
        <el-form-item label="姓名">
          <el-input v-model="addAddress.name"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="addAddress.phone"></el-input>
        </el-form-item>
        <el-form-item label="城市">
          <!-- elemtnui提供的选择的组件开始 -->
          <el-cascader
            size="large"
            :options="options"
            v-model="selectedOptions"
          >
          </el-cascader>
          <!-- elemtnui提供的选择的组件开始结束 -->
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="detailedAddress"></el-input>
        </el-form-item>
      </el-form>
      <!-- 添加地址表单结束 -->
      <div style="margin-left: 180px">
        <el-button type="primary" @click="closeAddDialog1">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加地址结束 -->
    <!-- --------------------- -->
    <!-- --------------------- -->
    <!-- 编辑地址开始 -->
    <el-dialog
      title="编辑地址"
      :visible.sync="dialogVisible2"
      width="30%"
      :before-close="handleClose2"
    >
      <!-- 编辑地址表单开始 -->
      <el-form label-position="right" label-width="80px" :model="editAddress">
        <el-form-item label="姓名">
          <el-input v-model="editAddress.name"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="editAddress.phone"></el-input>
        </el-form-item>
        <el-form-item label="城市">
          <!-- elemtnui提供的选择的组件开始 -->
          <el-cascader
            size="large"
            :options="options"
            v-model="selectedOptions"
          >
          </el-cascader>
          <!-- elemtnui提供的选择的组件开始结束 -->
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="detailedAddress"></el-input>
        </el-form-item>
      </el-form>
      <!--编辑地址表单结束 -->
      <div style="margin-left: 180px">
        <el-button type="primary" @click="closeEditDialog2">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑地址结束 -->
  </div>
</template>
    
  <script>
import { pcaTextArr } from "element-china-area-data";
import {
  getAddress,
  addAddress,
  delAddress,
  getAddressById,
  editAddress,
} from "@/api/addressMG";
export default {
  name: "AddressView",
  data() {
    return {
      dialogVisible1: false, //添加界面的地址弹出框
      dialogVisible2: false, //编辑界面的地址弹出框
      options: pcaTextArr, //elementui提供的省市区三级数据
      address: [], //数据库查出来的地址，查出来要先把 "%/"去掉取前三个存入selectedOptions1--待定
      addAddress: {
        //这是添加的地址的表单，拼接后的
        userId: localStorage.getItem("userId"),
        name: "",
        detailedAddress: "", //手填的详细地址，用addDetails: []和selectedOptions: [],拼接的
        phone: "",
      },
      editAddress: {},
      detailedAddress: "", //手填的详细地址
      selectedOptions: [], //选择的省市区，这两个后面要拼接到一起,然后赋值给添加表单里面
    };
  },

  methods: {
    handleClose2() {
      this.editAddress = {};
      this.detailedAddress = "";
      this.selectedOptions = [];
      this.dialogVisible2 = false;
    },
    async closeEditDialog2() {
      //这里是点击添加地址的dialog的下面的确认按钮的事件
      //这里先把this.detailedAddress和this.selectedOptions拼接起来，然后再把this.addAddress作为参数传递给后端
      //字符串拼接
      if (
        //验证成功返回true，就执行拼接操作并请求后端添加
        this.verifyForm(
          this.editAddress.name,
          this.editAddress.phone,
          this.selectedOptions,
          this.detailedAddress
        )
      ) {
        var loc = "";
        for (let i = 0; i < this.selectedOptions.length; i++) {
          loc = loc + this.selectedOptions[i] + "%/";
        }
        this.editAddress.detailedAddress = loc + this.detailedAddress;
        await editAddress(this.editAddress).then((res) => {
          if (res.data.code == 200) {
            this.$message.success(res.data.msg);
            this.editAddress = {};
            this.detailedAddress = "";
            this.selectedOptions = [];
            this.getAddresses();
            this.dialogVisible2 = false;
          } else {
            this.$message.error(res.data.msg);
          }
        });
        console.log(this.editAddress);
      } else return; //验证没成功就返回
    },
    async openDialog2(id) {
      //这里是打开编辑地址界面的表单
      //先获取到选择的这行地址的信息
      await getAddressById(id).then((res) => {
        if (res.data.code == 200) {
          // this.editAddress = res.data.data
          // console.log(res.data.data)
          let address = res.data.data.detailedAddress.split("%/"); //把从数据库获取到的地址详细信息拆分按照  %/，
          this.selectedOptions = address.slice(0, 3); //取前三个作为国家标准省市区的地址
          this.detailedAddress = address.slice(3).join(""); //后面的所有作为一个整体视作详细信息
          this.editAddress = res.data.data;
          //获取这行地址成功就显示编辑界面的表单
          this.dialogVisible2 = true;
        } else {
          this.$message.error(res.data.code + "::" + res.data.msg);
        }
      });
    },
    handleDelete(addressId) {
      delAddress(addressId).then((res) => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
          this.getAddresses();
        } else {
          this.$message.data(res.data.code + "::" + res.data.msg);
        }
      });
    },
    verifyForm(name, phone, selectedOptions, detailedAddress) {
      //验证添加和编辑的表单的数据的合法性
      if (name == "" || name == null) {
        this.$message.error("请输入收货人姓名");
        return false;
      }
      let testPhone = /^1[3-9]\d{9}$/;
      if (testPhone.test(phone) == false) {
        this.$message.error("请正确输入手机号");
        return false;
      }
      if (selectedOptions.length == 0 || selectedOptions == null) {
        this.$message.error("请选择您的城市");
        return false;
      }

      if (detailedAddress == "" || detailedAddress == null) {
        this.$message.error("请输入详细地址");
        return false;
      }
      return true;
    },
    async closeAddDialog1() {
      //这里是点击添加地址的dialog的下面的确认按钮的事件
      //这里先把this.detailedAddress和this.selectedOptions拼接起来，然后再把this.addAddress作为参数传递给后端
      //字符串拼接
      if (
        //验证成功返回true，就执行拼接操作并请求后端添加
        this.verifyForm(
          this.addAddress.name,
          this.addAddress.phone,
          this.selectedOptions,
          this.detailedAddress
        )
      ) {
        var loc = "";
        for (let i = 0; i < this.selectedOptions.length; i++) {
          loc = loc + this.selectedOptions[i] + "%/";
        }
        this.addAddress.detailedAddress = loc + this.detailedAddress;
        console.log(this.addAddress);
        await addAddress(this.addAddress).then((res) => {
          if (res.data.code == 200) {
            this.$message.success("地址添加成功!!!");
            this.getAddresses(); //添加成功就重新执行地址
          } else this.$message.error(res.data.code + ":" + res.data.msg);
        });
      } else return; //验证没成功就返回

      //下面是重置添加表单数据和选择的地址数据
      this.addAddress.name = "";
      this.addAddress.detailedAddress = "";
      this.addAddress.phone = "";
      this.detailedAddress = "";
      this.selectedOptions = [];
      this.dialogVisible1 = false;
    },
    handleClose1(done) {
      //这里是点击添加dialog右上角的×，记得清空表单
      //这里是点击添加地址的dialog的下面的确认按钮的事件
      //这里先把this.detailedAddress和this.selectedOptions拼接起来，然后再把this.addAddress作为参数传递给后端
      this.addAddress.name = "";
      this.addAddress.detailedAddress = "";
      this.addAddress.phone = "";
      this.detailedAddress = "";
      this.selectedOptions = [];
      this.dialogVisible1 = false;
      done();
    },
    openDialog1() {
      //打开dialog1，即添加界面的地址框
      this.dialogVisible1 = true;
    },
    async getAddresses() {
      //获取自己的所有地址
      await getAddress(localStorage.getItem("userId")).then((res) => {
        if (res.data.code) {
          res.data.data.forEach((address) => {
            address.detailedAddress = address.detailedAddress.replace(
              /%\//g,
              ""
            );
          });
          this.address = res.data.data;
          // console.log(res.data.data);
          // console.log((res.data.data).id)
        } else {
          this.$message.error(res.data.code + "::" + res.data.msg);
        }
      });
    },
    // handleChange() {
    //   //处理地址，别急这里
    //   var loc = "";
    //   for (let i = 0; i < this.selectedOptions.length; i++) {
    //     loc = loc + this.selectedOptions[i] + "%/";
    //   }
    //   console.log(loc); //打印区域码所对应的属性值即中文地址
    // },
  },
  mounted() {
    this.getAddresses();
  },
};
</script>